using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HttpModels;

/// <summary>
/// HTTP网络收发模拟器
/// </summary>
public class HttpNetworkSimulator : MonoBehaviour
{
    // 单例实例
    private static HttpNetworkSimulator _instance;
    public static HttpNetworkSimulator Instance
    {
        get
        {
            return _instance;
        }
    }

    // 模拟网络延迟(毫秒)
    [SerializeField] private int minDelay = 100;
    [SerializeField] private int maxDelay = 500;

    // 模拟服务器数据
    private Dictionary<string, PlayerInfo> playerDatabase = new Dictionary<string, PlayerInfo>();
    private Dictionary<string, string> userTokens = new Dictionary<string, string>();

    private System.Random random = new System.Random();

    void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(gameObject);
            return;
        }

        _instance = this;
        DontDestroyOnLoad(gameObject);

        // 初始化模拟数据库
        InitializeDatabase();
    }

    /// <summary>
    /// 初始化模拟数据库
    /// </summary>
    private void InitializeDatabase()
    {
        // 添加一些测试用户
        var player1 = new PlayerInfo
        {
            playerId = 10001,
            nickname = "玩家1",
            level = 15,
            exp = 12500,
            gold = 5000,
            diamond = 200
        };

        // 添加道具
        player1.items.Add(new ItemInfo { itemId = 101, count = 5 });
        player1.items.Add(new ItemInfo { itemId = 102, count = 3 });

        // 添加英雄
        player1.heroes.Add(new HeroInfo { heroId = 1, level = 10, star = 3 });
        player1.heroes.Add(new HeroInfo { heroId = 2, level = 8, star = 2 });

        playerDatabase["player1"] = player1;
        userTokens["player1_token"] = "player1";

        var player2 = new PlayerInfo
        {
            playerId = 10002,
            nickname = "玩家2",
            level = 25,
            exp = 45000,
            gold = 12000,
            diamond = 500
        };

        player2.items.Add(new ItemInfo { itemId = 101, count = 10 });
        player2.items.Add(new ItemInfo { itemId = 103, count = 2 });
        player2.heroes.Add(new HeroInfo { heroId = 1, level = 15, star = 4 });
        player2.heroes.Add(new HeroInfo { heroId = 3, level = 12, star = 3 });

        playerDatabase["player2"] = player2;
        userTokens["player2_token"] = "player2";
    }

    /// <summary>
    /// 处理登录请求
    /// </summary>
    /// <param name="jsonRequest">JSON格式的登录请求</param>
    /// <param name="callback">回调函数</param>
    public void ProcessLoginRequest(string jsonRequest, Action<string> callback)
    {
        Debug.Log($"收到登录请求: {jsonRequest}");

        // 反序列化请求数据
        var request = JsonUtil.FromJson<LoginRequest>(jsonRequest, new LoginRequest("", "", "", ""));

        // 模拟网络延迟
        int delay = random.Next(minDelay, maxDelay + 1);
        StartCoroutine(DelayedResponse(delay, () => {
            string jsonResponse = GenerateLoginResponse(request);
            Debug.Log($"发送登录响应: {jsonResponse}");
            callback?.Invoke(jsonResponse);
        }));
    }

    /// <summary>
    /// 生成登录响应
    /// </summary>
    /// <param name="request">登录请求</param>
    /// <returns>JSON格式的登录响应</returns>
    private string GenerateLoginResponse(LoginRequest request)
    {
        var response = new LoginResponse();
        response.code = 0;
        response.message = "登录成功";

        // 简单的验证逻辑
        if (string.IsNullOrEmpty(request.username) || string.IsNullOrEmpty(request.password))
        {
            response.code = 1;
            response.message = "用户名或密码不能为空";
        }
        else if (!playerDatabase.ContainsKey(request.username))
        {
            response.code = 2;
            response.message = "用户不存在";
        }
        else if (request.password != "123456") // 简单的密码验证
        {
            response.code = 3;
            response.message = "密码错误";
        }
        else
        {
            // 登录成功，返回玩家信息
            response.playerInfo = playerDatabase[request.username];
            response.token = $"{request.username}_token";
        }

        return JsonUtil.ToJson(response);
    }

    /// <summary>
    /// 延迟响应协程
    /// </summary>
    /// <param name="delayMs">延迟毫秒数</param>
    /// <param name="action">要执行的操作</param>
    /// <returns></returns>
    private IEnumerator DelayedResponse(int delayMs, Action action)
    {
        yield return new WaitForSeconds(delayMs / 1000f);
        action?.Invoke();
    }

    /// <summary>
    /// 获取玩家信息(通过token)
    /// </summary>
    /// <param name="token">登录令牌</param>
    /// <returns>JSON格式的玩家信息</returns>
    public string GetPlayerInfoByToken(string token)
    {
        if (userTokens.ContainsKey(token) && playerDatabase.ContainsKey(userTokens[token]))
        {
            var playerInfo = playerDatabase[userTokens[token]];
            return JsonUtil.ToJson(playerInfo);
        }
        return JsonUtil.ToJson(new BaseResponse { code = 1, message = "无效的令牌" });
    }
}